package com.kitkat.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.alibaba.fastjson.JSONObject;

public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper{
	
	private static String defaultParamName = "data";
	private Map<String,String[]> paramMap;
	
	public MyHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		try {
			super.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.paramMap = new HashMap<String,String[]>();
		String token = super.getHeader("token");
		if(token!=null){
			this.paramMap.put("token", new String[]{token});
		}
		Enumeration<String> paramNames = super.getParameterNames();
		while(paramNames.hasMoreElements()){
			String key = paramNames.nextElement();
			String[] value = super.getParameterValues(key);
			if(!key.equals(defaultParamName)||(value.length!=1)){
				this.paramMap.put(key, value);
			}
			else{
				transform(value[0]);
			}
		}
		
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(super.getInputStream()));
			String line = null;
			while((line=br.readLine())!=null){
				transform(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void transform(String value) {
		Map<String,Object> map = JSONObject.parseObject(value, Map.class);
		Iterator<String> it = map.keySet().iterator();
		while(it.hasNext()){
			String key = it.next();
			String _value = map.get(key).toString();
			if(!key.equals(defaultParamName)){
				this.paramMap.put(key, new String[]{_value});
			}
			else{
				transform(_value);
			}
		}
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		return this.paramMap;
	}

	@Override
	public String[] getParameterValues(String name) {
		return this.paramMap.get(name);
	}
}
